package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.controller.vo.EvaluationsVo;
import com.example.controller.vo.Result;
import com.example.entity.CommentLike;
import com.example.entity.Evaluations;
import com.example.entity.User;
import com.example.mapper.CommentLikeMapper;
import com.example.mapper.EvaluationsMapper;
import com.example.mapper.UserMapper;
import com.example.service.CommentLikeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
@Service
public class CommentLikeServiceImpl implements CommentLikeService {
    @Autowired
    private CommentLikeMapper commentLikeMapper;

    @Autowired
    private EvaluationsMapper evaluationsMapper;

    @Autowired
    private UserMapper userMapper; // 用于检查用户是否存在

    /**
     * 点赞/取消点赞切换
     */
    @Override
    @Transactional
    public Result toggleLike(Integer id, Integer userId) {
        // 1. 业务层校验：检查评论和用户是否存在
        Evaluations comment = evaluationsMapper.selectByIdWithRelations(id);
        if (comment == null) {
            return Result.failed("评论不存在");
        }
        User user = userMapper.selectById(userId);
        if (user == null) {
            return Result.failed("用户不存在");
        }
        // 2. 检查当前点赞状态
        int likedCount = commentLikeMapper.checkLiked(id, userId);
        boolean isLiked = likedCount > 0;
        if (isLiked) {
            // 3. 已点赞：执行取消点赞
            QueryWrapper<CommentLike> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("comment_id", id).eq("user_id", userId);
            commentLikeMapper.delete(queryWrapper);
            // 减少点赞数
            evaluationsMapper.decrementLikeCount(id);
            return Result.success( "false");
        } else {
            // 4. 未点赞：执行点赞
            try {
                CommentLike like = new CommentLike();
                like.setCommentId(id);
                like.setUserId(userId);
                like.setCreateTime(LocalDateTime.now());
                commentLikeMapper.insert(like);
                // 增加点赞数
                evaluationsMapper.incrementLikeCount(id);
                return Result.success( "true");
            } catch (DuplicateKeyException e) {
                // 并发场景下，唯一索引冲突处理
                return Result.failed("操作频繁，请稍后再试");
            }
        }
    }

    /**
     * 查询用户对评论的点赞状态
     */
    @Override
    public Result getLikedStatus(Integer commentId, Integer userId) {
        int count = commentLikeMapper.checkLiked(commentId, userId);
        return Result.success(count > 0);
    }
}
